<?php

namespace Xrfg\Api\Trading\Spot\Console;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use function GuzzleHttp\Promise\settle;

class Huobi extends Command
{
    public $signature = 'huobi';

    public $description = '获取火币K线数据';

    public function handle()
    {
        $symbols = config('huobi');
        $klineTypes = config('kline.type');

        $config = [];
        if (app()->isLocal()) {
            $config['proxy'] = 'http://192.168.2.222:1087';
        }

        $http = new Client($config);
        $promises = [];
        foreach (array_keys($symbols) as $symbol) {
            // K线
            foreach (array_keys($klineTypes) as $type) {
                $kline = $http->getAsync('https://api.huobi.pro/market/history/kline', [
                    'query' => [
                        'symbol' => strtolower(str_replace('/', '', $symbol)),
                        'period' => $type,
                        'size' => 500,
                    ],
                ]);
                $promises['kline:'.$symbol.':'.$type] = $kline;
            }
        }
        $results = settle($promises)->wait();

        foreach (array_keys($symbols) as $symbol) {
            foreach (array_keys($klineTypes) as $type) {
                if ('fulfilled' === $results['kline:'.$symbol.':'.$type]['state']) {
                    /** @var Response $response */
                    $response = $results['kline:'.$symbol.':'.$type]['value'];
                    $this->klineHandle($response, $klineTypes, $type, $symbol);
                }
            }
        }
    }

    private function klineHandle(Response $response, array $klineTypes, $type, $symbol): void
    {
        $result = json_decode($response->getBody()->getContents(), true);
        $kline = [];
        foreach ($result['data'] as $item) {
            $kline[] = [
                'time_open' => $item['id'],
                'time_close' => $item['id'] + $klineTypes[$type] * 60,
                'price_open' => $item['open'],
                'price_close' => $item['close'],
                'price_high' => $item['high'],
                'price_low' => $item['low'],
                'trades_number' => $item['amount'],
                'trades_total' => $item['vol'],
                'trades_count' => $item['count'],
            ];
        }
        Cache::forever('huobi:kline:'.$symbol.':'.$type, $kline);
    }
}
